package com.jokins.admin.vue.user.action;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jokins.admin.vue.user.actioncontext.SysUserRePasswordDoc;
import com.jokins.admin.vue.user.mapper.SysUserMapper;
import com.jokins.admin.vue.user.utils.FixedHashPasswordUtils;
import com.jokins.common.actions.action.ActionContext;
import com.jokins.common.actions.action.BaseAction;
import com.jokins.common.actions.exception.BusinessException;
import com.jokins.common.entry.vue.user.SysUser;
import com.jokins.common.util.BusinessCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class SysUserRePasswordDocAction extends BaseAction<SysUserRePasswordDoc> {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    protected void process(SysUserRePasswordDoc actionContext) throws BusinessException {
        String id= actionContext.getId();
        String sourcePassword = FixedHashPasswordUtils.generateRandomString();
        String newPassword = FixedHashPasswordUtils.sha256Hash(sourcePassword);
        UpdateWrapper<SysUser> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id);
        updateWrapper.set("password",sourcePassword);
        updateWrapper.set("salt",newPassword);
        int rowsAffected =  sysUserMapper.update(null, updateWrapper);
        if (rowsAffected == 0) {
            throw new BusinessException("Failed to update password", BusinessCode.SYSTEM_ERROR);
        }else{
            log.info("重置密码正确，密码为：{}",newPassword);
            actionContext.setResult(ActionContext.RESULT_DOC_KEY, sourcePassword);
        }
    }
}
